package cn.webrx.bs.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * <p>
 * 功能：图像文件处理（验证码、缩略图、水印文字、水印图标、裁剪图某部分）
 * <h5>2017-9-19</h5>
 * </p>
 *
 * @author webrx
 * @version 1.0
 */
public class ImgUtil {


    private String src;
    private BufferedImage i;
    private int w;
    private int h;

    /**
     *
     */
    public ImgUtil() {
    }

    public void setImages(String src) {
        this.src = src;
        File f = new File(src);
        if (f.exists()) {
            try {
                this.i = ImageIO.read(new File(src));
                this.w = this.i.getWidth();
                this.h = this.i.getHeight();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param src
     */
    public ImgUtil(String src) {
        this.src = src;
        File f = new File(src);
        if (f.exists()) {
            try {
                this.i = ImageIO.read(new File(src));
                this.w = this.i.getWidth();
                this.h = this.i.getHeight();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param alpha
     * @return
     */
    public Color getColor(int alpha) {
        Random r = new Random();
        Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255), alpha);
        return c;
    }

    /**
     * @return
     */
    public Color getColor() {
        Random r = new Random();
        Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255), r.nextInt(255));
        return c;
    }

    /**
     * @param text
     * @param fontsize
     * @param color
     * @param pos
     * @param flag
     * @param padding
     * @param extt
     */
    public void text(String text, int fontsize, String color, int pos, boolean flag, int padding, String extt) {
        Graphics2D g = (Graphics2D) this.i.getGraphics();
        Font font = new Font("黑体", Font.BOLD, fontsize);
        g.setFont(font);
        FontMetrics metrics = g.getFontMetrics(g.getFont());
        int th = metrics.getHeight();
        int tw = metrics.stringWidth(text);
        int x = padding;
        int y = padding;
        switch (pos) {
            case 1:
                x = padding;
                y = padding + th;
                break;
            case 2:
                x = (int) ((w - tw) / 2);
                y = padding + th;
                break;
            case 3:
                x = w - tw - padding;
                y = padding + th;
                break;
            case 4:
                x = padding;
                y = (int) ((h - th) / 2);
                break;
            case 5:
                x = (int) ((w - tw) / 2);
                y = (int) ((h - th) / 2);
                break;
            case 6:
                x = w - tw - padding;
                y = (int) ((h - th) / 2);
                break;
            case 7:
                x = padding;
                y = h - padding;
                break;
            case 8:
                x = (int) ((w - tw) / 2);
                y = h - padding;
                break;
            case 9:
                x = w - tw - padding;
                y = h - padding;
                break;
            default:
                Random r = new Random();
                x = r.nextInt(w - tw - padding - padding) + padding;
                y = r.nextInt(h - padding - padding - th) + (padding + th);
                break;
        }
        if ("white".equalsIgnoreCase(color)) {
            g.setColor(new Color(255, 255, 255, 150));
        } else if ("black".equalsIgnoreCase(color)) {
            g.setColor(new Color(0, 0, 0, 150));
        } else if ("red".equalsIgnoreCase(color)) {
            g.setColor(new Color(255, 0, 0, 150));
        } else if ("green".equalsIgnoreCase(color)) {
            g.setColor(new Color(0, 255, 0, 150));
        } else if ("blue".equalsIgnoreCase(color)) {
            g.setColor(new Color(0, 0, 255, 150));
        } else {
            g.setColor(this.getColor());
        }
        g.drawString(text, x, y);
        if (flag) {
            try {
                ImageIO.write(this.i, "jpg", new File(this.src));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                ImageIO.write(this.i, "jpg", new File(this.src.replaceAll(this.getExt(true), extt + ".jpg")));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        g.dispose();
    }

    /**
     * <p>
     * 实现缩略图功能，ww,hh flag为true 高度按比例，fg为true覆盖原图
     * </p>
     *
     * @param ww
     * @param hh
     * @param flag
     * @param fg
     */
    public void thumb(int ww, int hh, boolean flag, boolean fg) {
        try {
            // 如果注释下边高度计算，则采用指定宽高
            if (flag) {
                hh = (int) ((double) ww / w * h);
            }
            // 建立指定尺寸的缓存图像
            BufferedImage ii = new BufferedImage(ww, hh, BufferedImage.TYPE_INT_RGB);
            Graphics g = ii.getGraphics();
            g.drawImage(this.i, 0, 0, ww, hh, null);
            if (fg) {
                ImageIO.write(ii, "jpg", new File(this.src));
            } else {
                ImageIO.write(ii, "jpg", new File(this.src.replaceAll(this.getExt(true), ww + "_" + hh + ".jpg")));
            }
            g.dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * <p>
     * 裁剪图像某部分，如果flag为true,裁剪出的图像覆盖原图
     * </p>
     *
     * @param x
     * @param y
     * @param ww
     * @param hh
     * @param flag
     */
    public void crop(int x, int y, int ww, int hh, boolean flag) {
        try {
            // 建立指定尺寸的缓存图像
            BufferedImage ii = new BufferedImage(ww, hh, BufferedImage.TYPE_INT_RGB);
            Graphics g = ii.getGraphics();
            g.drawImage(this.i, 0, 0, ww, hh, x, y, x + ww, y + hh, null);// 裁剪图片某部分
            if (flag) {
                ImageIO.write(ii, "jpg", new File(this.src));
            } else {
                ImageIO.write(ii, "jpg", new File(this.src.replaceAll(this.getExt(true), ww + "_" + hh + ".jpg")));
            }
            g.dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void check() {

    }

    /**
     * <p>
     * 返回操作图像文件的扩展名，如jpg
     * </p>
     *
     * @return
     */
    public String getExt() {
        return this.getExt(false);
    }

    /**
     * <p>
     * 返回操作图像文件的扩展名，如参数flag 为true 返回 .jpg 为false 返回jpg不带点
     * </p>
     *
     * @param flag
     * @return
     */
    public String getExt(boolean flag) {
        String ext = this.src.substring(this.src.lastIndexOf(".")).toLowerCase();
        return flag ? ext : ext.substring(1);
    }

    public String getFileName() {
        String fn = null;
        String separator = File.separator;
        if (this.src.indexOf("/") != -1)
            separator = "/";
        int pos = this.src.lastIndexOf(separator);
        if (pos != -1) {
            fn = this.src.substring(pos + 1).toLowerCase();
        }
        return fn;
    }

    /**
     * <p>
     * 功能：
     * </p>
     *
     * @param sourcefile
     * @param logofile
     */
    public void logo(String logofile) {
        this.logo(logofile, 5, true, 15, "_logo");
    }

    /**
     * <p>
     * 功能：
     * </p>
     *
     * @param sourcefile
     * @param logofile
     * @param pos
     * @param flag
     * @param padding
     * @param ext
     */
    public void logo(String logofile, int pos, boolean flag, int padding, String ext) {
        try {
            BufferedImage logo = ImageIO.read(new File(logofile));
            Graphics g = i.getGraphics();
            int x = padding;
            int y = padding;
            switch (pos) {
                case 1:
                    x = padding;
                    y = padding;
                    break;
                case 2:
                    x = (int) ((i.getWidth() - logo.getWidth()) / 2);
                    y = padding;
                    break;
                case 3:
                    x = i.getWidth() - logo.getWidth() - padding;
                    y = padding;
                    break;
                case 4:
                    x = padding;
                    y = (int) ((i.getHeight() - logo.getHeight()) / 2);
                    break;
                case 5:
                    x = (int) ((i.getWidth() - logo.getWidth()) / 2);
                    y = (int) ((i.getHeight() - logo.getHeight()) / 2);
                    break;
                case 6:
                    x = i.getWidth() - logo.getWidth() - padding;
                    y = (int) ((i.getHeight() - logo.getHeight()) / 2);
                    break;
                case 7:
                    x = padding;
                    y = i.getHeight() - logo.getHeight() - padding;
                    break;
                case 8:
                    x = (int) ((i.getWidth() - logo.getWidth()) / 2);
                    y = i.getHeight() - logo.getHeight() - padding;
                    break;
                case 9:
                    x = i.getWidth() - logo.getWidth() - padding;
                    y = i.getHeight() - logo.getHeight() - padding;
                    break;
                default:
                    Random r = new Random();
                    x = r.nextInt(i.getWidth() - logo.getWidth() - padding) + padding;
                    y = r.nextInt(i.getHeight() - logo.getHeight() - padding) + padding;
                    break;
            }
            g.drawImage(logo, x, y, null);
            String filename = this.getFileName();
            if (flag) {
                ImageIO.write(i, this.getExt(), new File(this.src));
            } else {
                ImageIO.write(i, this.getExt(), new File(this.src.replaceAll(filename, filename + ext)));
            }
            g.dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

